package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.anno.LogOperation;
import com.itheima.mapper.StuMapper;
import com.itheima.pojo.ClassOption;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.StuRequestParam;
import com.itheima.pojo.Student;
import com.itheima.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class StuServiceImpl implements StuService {
    @Autowired
    private StuMapper stuMapper;

    /**
     * 条件分页查询学生信息
     * */
    @Override
    public PageResult<Student> page(StuRequestParam stuRequestParam) {
        //设置分页参数
        PageHelper.startPage(stuRequestParam.getPage(), stuRequestParam.getPageSize());

        //调用mapper层方法查询数据
        List<Student> stuList = stuMapper.list(stuRequestParam);

        //封装成PageResult对象并返回
        Page<Student> result = (Page<Student>) stuList;
        return new PageResult<>(result.getTotal(), result.getResult());
    }

    /**
     * 批量删除学生信息
     * */
    @LogOperation
    @Override
    public void deleteByIds(List<Integer> ids) {
        //调用mapper层方法，删除指定id的学员
        stuMapper.deleteByIds(ids);
    }

    /**
     * 添加学生信息
     * */
    @LogOperation
    @Override
    public void add(Student student) {
        //基础数据补全
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        //调用mapper层方法，添加学生信息
        stuMapper.add(student);
    }

    /**
     * 根据id查询学生信息
     * */
    @Override
    public Student selectById(Integer id) {
        return stuMapper.selectById(id);
    }

    /**
     * 修改学生信息
     * */
    @LogOperation
    @Override
    public void update(Student student) {
        //修改更新时间
        student.setUpdateTime(LocalDateTime.now());

        //调用mapper层方法，修改学生信息
        stuMapper.update(student);
    }

    @Override
    public void updateViolation(Integer id, Integer score) {
        //调用mapper层方法，修改学生信息（修改更新时间）
        stuMapper.updateViolation(id, score);
    }

    /**
     * 获取学生的学历统计报表
    * */
    @Override
    public List<Map<String, Object>> getStuDegreeReport() {
        //调用mapper层方法，获取学历统计报表
        return stuMapper.getStuDegreeReport();
    }

    /**
     * 获取班级名称以及对应人数
     * */
    @Override
    public ClassOption getStudentCountData() {
        //调用mapper层方法，获取班级名称以及对应人数
        List<Map<String, Object>> studentCountData = stuMapper.getStudentCountData();

        //遍历集合，获取班级名称以及对应人数并封装到List集合中
        List<String> clazzList = studentCountData.stream().map(map -> map.get("clazzName").toString()).toList();
        List<Long> dataList = studentCountData.stream().map(map -> (Long)map.get("nums")).toList();

        //将两个List集合封装到ClassOption对象中，并返回
        return new ClassOption(clazzList, dataList);
    }
}
